package ms.unicorn.palette;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteEntry;

public class PaletteGroup extends PaletteItem {
	private String label, description;
	private List<PaletteTool> tools;

	public void setLabel(String label) {
		this.label = label;
	}

	public String getLabel() {
		return label;
	}

	public List<PaletteTool> getTools() {
		return tools != null ? tools
				: (tools = new ArrayList<PaletteTool>());
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDescription() {
		return description != null ? description : label;
	}

	public PaletteEntry createPaletteContainer() {
		PaletteDrawer paletteContainer = new PaletteDrawer(getLabel());
		paletteContainer.setId(getId()); //$NON-NLS-1$
		paletteContainer.setDescription(getDescription());
		for (PaletteTool tool : getTools())
			if (!tool.isRemoved()) {
				PaletteEntry entry = tool.createPaletteEntry();
				if (entry != null) paletteContainer.add(entry);
			}
		return paletteContainer;
	}

	public static void createGroupFromConfigItem(
			IConfigurationElement item, List<PaletteGroup> groups,
			Map<String, PaletteItem> itemMap) throws Exception {

		String id = item.getAttribute("id");
		PaletteGroup group = null;
		Object groupObj = id != null ? itemMap.get(id) : null;
		if (groupObj == null) {
			groups.add(group = new PaletteGroup());
			if (id != null && id.length() > 0)
				itemMap.put(id, group);
		} else if (groupObj instanceof PaletteGroup)
			group = (PaletteGroup) groupObj;
		else
			throw new Exception("The tool id " + id
					+ " has beed used as a tool entry, not group.");

		group.setId(id);
		for (String attrName : item.getAttributeNames())
			if (attrName.equalsIgnoreCase("label"))
				group.setLabel(item.getAttribute(attrName));

		for (IConfigurationElement child : item.getChildren(PALETTE_TOOL)) {
			PaletteTool.createToolFromConfigItem(child, group, itemMap);
		}

	}
}
